IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('MD3.RunIndexes'))
BEGIN
	DROP PROCEDURE MD3.RunIndexes
END
GO

CREATE Procedure MD3.RunIndexes
AS
    
BEGIN

    SET QUOTED_IDENTIFIER ON
    SET NOCOUNT ON 

	/*
		Runs all Indexes found in MD3.Indexes
		this is called from/in the Indexes folder, after the MD3.Indexes table is loaded

	*/

	

DECLARE 
	@IndexName SYSNAME,
	@SchemaName VARCHAR(256),
	@TableName VARCHAR(256) ,
	@KeyColumns VARCHAR(MAX) ,
	@IncludedColumns		VARCHAR(MAX) ,
    @IsClustered	BIT ,
	@IsUnique		BIT,
	@FGorPartitionScheme VARCHAR(MAX),
	@IdxFillFactor int ,
	@IsPadded BIT ,
	@CompressionSetting VARCHAR(50),
	@DropIndex BIT 

	
DECLARE CurIndexes CURSOR FOR 	
	--get a list of indexes
	SELECT 
		IndexName,
		SchemaName ,
		TableName ,
		KeyColumns  ,
		IncludedColumns,
		IsClustered	  ,
		IsUnique ,
		FGorPartitionScheme ,
		IdxFillFactor  ,
		IsPadded  ,
		CompressionSetting ,
		DropIndex 
	FROM MD3.Indexes
	ORDER BY Id
OPEN CurIndexes
FETCH NEXT FROM curIndexes INTO 
	@IndexName,
	@SchemaName ,
	@TableName ,
	@KeyColumns  ,
	@IncludedColumns,
    @IsClustered	 ,  
	@IsUnique	,
	@FGorPartitionScheme ,
	@IdxFillFactor  ,
	@IsPadded  ,
	@CompressionSetting ,
	@DropIndex ;

WHILE @@FETCH_STATUS = 0
BEGIN 

	EXEC MD3.CreateIndex  
		@SchemaName			=@SchemaName,
		@TableName			=@TableName,
		@IndexName			=@IndexName,
		@IndexKeyColumns	=@KeyColumns,
		@IncludedColumns	=@IncludedColumns,
		@FileGroupOrPartition =@FGorPartitionScheme,
		@IsUnique			=@IsUnique,
		@IsClustered		=@IsClustered,
		@FillFactor			=@IdxFillFactor,
		@PadIndex			=@IsPadded,
		@DropIndex			=@DropIndex,
		@DataCompressionType =@CompressionSetting
	;

	
	
	FETCH NEXT FROM curIndexes INTO 
		@IndexName,
		@SchemaName ,
		@TableName ,
		@KeyColumns  ,
		@IncludedColumns,
		@IsClustered	 ,  
		@IsUnique	,
		@FGorPartitionScheme ,
		@IdxFillFactor  ,
		@IsPadded  ,
		@CompressionSetting ,
		@DropIndex ;
END

CLOSE curIndexes
DEALLOCATE curIndexes



END
GO
